package com.qzxy.premiumhotelsystem.utils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static com.qzxy.premiumhotelsystem.common.constant.CaptchaConstant.LOGIN_V_CODE;
import static com.qzxy.premiumhotelsystem.common.constant.CaptchaConstant.UPDATE_V_CODE;

/**
 * @Author: iQNRen
 * @Description: 验证码管理
 * @Date: 2024/9/17 16:32 周二
 * @Version: 1.0
 */
public class KeysUtil {
    private static final ConcurrentHashMap<String, String> captchaMap = new ConcurrentHashMap<>();
    private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public static void addCaptcha(String key, String value, long expireTimeInSeconds) {
        if (key == null || value == null) {
            throw new IllegalArgumentException("Key and value must not be null");
        }
        try {
            captchaMap.put(key, value);
            scheduler.schedule(() -> {
                captchaMap.remove(key);
                System.out.println("Removed captcha for key: " + key);
            }, expireTimeInSeconds, TimeUnit.SECONDS);
            System.out.println("captchaMap: " + captchaMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getCaptcha(String key) {
        return captchaMap.get(key);
    }

    public static boolean validateCaptcha(String key, String inputCode) {
        String storedCode = KeysUtil.getCaptcha(key);
        if (key.contains(LOGIN_V_CODE) || key.contains(UPDATE_V_CODE)) {
            captchaMap.remove(key);
            System.out.println("验证码已删除");
        }
        return inputCode != null && inputCode.equals(storedCode);
    }

    public static String removeCaptcha(String key) {
        return captchaMap.remove(key);
    }

}


